<?php

require_once '../library/MAPI/AlloCine.php';
require_once "MainController.php";

/**
 * Contrôleur par défaut
 *
 * @package Controller
 */
class SearchController extends MainController {

    /**
     * Affichage du formulaire
     *
     * @return null
     */
    public function indexAction() {

        // .js
        $this->view->headScript()->appendFile($this->view->baseUrl() . "/js/search.js");
    }

    /**
     * Recherche de film
     * GET: q=...
     * http://localhost/mediaglobe/search/search/title/ted
     * @return null
     */
    public function searchAction() {

        $params = $this->_request->getParams();

        if (!isset($params['title'])) {
            $this->_response->clearBody();
            $this->_response->clearHeaders();
            $this->_response->setHttpResponseCode(406);
            return;
        }
        $param_title = $params['title'];
        $param_sort = isset($params['sort']) ? $params['sort'] : 'title';
        $param_order = isset($params['order']) ? $params['order'] : 'desc';

        // FIXME: mettre en app.ini
        $movie_cache_allow = false;
        $movie_cache_max = 3;

        // FILMS
        if ($movie_cache_allow) {
            if (isset($_SESSION['mediaglobe']['movies'][$param_title]))
                $finalResults = $_SESSION['mediaglobe']['movies'][$param_title];
            else {
                $finalResults = $this->searchMovies($param_title);
                if (count($_SESSION['mediaglobe']['movies']) > $movie_cache_max)
                    array_pop($_SESSION['mediaglobe']['movies']);
                $_SESSION['mediaglobe']['movies'][$param_title] = $finalResults;
            }
        }
        else
            $finalResults = $this->searchMovies($param_title);

//         $this->_logger->debug("== finalResults ==================================");
//         $this->_logger->debug(print_r($finalResults, true));
//         $this->_logger->debug("==================================================");

        $this->_helper->json($finalResults);
    }

    /**
     *
     * @param string $title
     */
    private function searchMovies($title) {

        $this->_logger->info("[searchMovies] recherche du film <$title>");

        $options = Zend_Registry::get('Zend_Config');
        $pluginName = $options['movie_plugin'];
        $pluginClass = "MAPI_$pluginName";
        $api = new $pluginClass();

        // Recherche via l'API
        $api_params['lang'] = substr($options['defaultLocale'], 0, 2);
        if (isset($options['proxy'])){
            $api_params['proxy'] = $options['proxy'];
        }
        $api->setParams($api_params);
        $apiMovies = $api->searchMovies($title);

        if (count($apiMovies) > 100)
            throw new ErrorException('too many');

        $apiMoviesList = "";
        foreach ($apiMovies as $apiMovie) {
            if ($apiMoviesList != "")
                $apiMoviesList .= ',';
            $apiMoviesList .= $apiMovie->id;
        }

        $movieMapper = new App_Model_MovieMapper();
        $userId = $this->_connection->id;

        // liste des ID (de l'api)
        $moviesAddedIdList = $movieMapper->getMoviesByUserByApiIdList($userId, $pluginName, $apiMoviesList);

        $this->_logger->debug("=== apiMoviesList =================");
        $this->_logger->debug($apiMoviesList);

        // On complete $apiMovies avec les $dbMovies communs
        $finalResults = array();
        foreach ($apiMovies as $apiMovie) { // MAPI_Model_Movie
//             $apiMovie->movieIdInDB = -1;
            //                 $this->_logger->debug("== dbMovies ===================================");
            //                 $this->_logger->debug(print_r($dbMovies, true));
//             foreach ($dbMovies as $dbMovie) { // array(idMovie, api_idMovie,, api avgRating)
//                 if ($dbMovie['api_idMovie'] == 'TMDB' && $apiMovie->id == $dbMovie['api_idMovie']) {
//                     $apiMovie->avgRating = $dbMovie['avgRating'];
//                     $apiMovie->movieIdInDB = $dbMovie['idMovie'];
//                 }
//             }
            $apiMovie->addedByUser = false;
            foreach ($moviesAddedIdList as $id) {
                if ($apiMovie->id == $id) {
//                     $apiMovie->avgRating = $dbMovie['avgRating'];
//                     $apiMovie->movieIdInDB = $dbMovie['idMovie'];
                    $apiMovie->addedByUser = true;
                    break;
                }
            }
            $finalResults[] = array(
                    'api_name' => $pluginName, //'TMDB',
                    'api_idMovie' => $apiMovie->id,
                    'title' => $apiMovie->o_title,
//                     'titleFr' => $apiMovie->title,
                    'year' => $apiMovie->production_year,
//                     'movieIdInDB' => $apiMovie->movieIdInDB,
                    'addedByUser' => $apiMovie->addedByUser,
            );
        }

//         if ($pluginName == 'TMDB') { // test

//             // Recherche dans la DB
// //             $titleParts = explode (' ' , $title); // TODO : Gerer 2 espaces
// //             $dbMovies = array(); // $movieMapper->getMoviesByTitle($titleParts); // contient des array(idMovie, api_idMovie, avgRating)

// //             $this->_logger->debug("=== getMoviesByApiIdList =================");
// //             $this->_logger->debug($test);


//             // On joint $dbMovie
//             foreach ($dbMovies as $dbMovie) { // array(idMovie, api_idMovie,, api avgRating)
//                 $found = false;
//                 foreach ($finalResults as $result) { // MAPI_Model_Movie
//                     if ($dbMovie['api'] == 'TMDB' && $result['api_idMovie'] == $dbMovie['api_idMovie']) {
//                         $found = true;
//                         break;
//                     }
//                 }
//                 if (!$found) {
//                     $newMovie = array(
//                         'api_name' => null,
//                         'api_idMovie' => null,
//                         'title' => 'COUCOU_FIXME',
//                         'titleFr' => 'COUCOU_FIXME',
//                         'year' => '',
//                         'movieIdInDB' => $apiMovie->movieIdInDB,

//                         'idMovieDB' => $dbMovie['idMovie'],
//                         'avgRating' => $dbMovie['avgRating'],
//                     );
//                     $finalResults[] = $newMovie;
//                 }
//             }
//         }

        $this->_logger->debug("=== search result =================");
        $this->_logger->debug($finalResults);

        return $finalResults;
    }











    /**
     *     FIXME gerer le nom de l'api en plus de l'id
     *
     * Recuperation des details d'un film
     * GET: api_id=...
     */
    public function getdetailsAction() {

        $params = $this->_request->getParams();
        if (!isset($params['api_id'])) {
            $this->_response->clearBody();
            $this->_response->clearHeaders();
            $this->_response->setHttpResponseCode(406);
            return;
        }

        $options = Zend_Registry::get('Zend_Config');
        $pluginName = $options['movie_plugin'];
        $pluginClass = "MAPI_$pluginName";
        $api = new $pluginClass();

        $api_params['lang'] = substr($options['defaultLocale'], 0, 2);
        if(isset($options['proxy'])) {
            $api_params['proxy'] = $options['proxy'];
        }

        $api->setParams($api_params);
        $myArrayofData = $api->getMovieDetails($params['api_id']);

        $this->_helper->json($myArrayofData);
    }

    /**
     * api_id et api_name
     * OU
     * db_id
     *
     * ex: 121734 : Las aventuras de Tadeo Jones
     *
     * http://localhost/mediaglobe/search/addmovie/api_name/tmdb/api_id/121734
     *
     * 72105
     *
     * http://localhost/mediaglobe/search/addmovie/db_id/7
     */
    public function addmovieAction() {

        try {

            $toReturn = array('code' => 0);
            $params = $this->_request->getParams();

//             $this->_logger->debug("=== addmovieAction ===");
//             $this->_logger->debug($params);

            if (isset($params['api_name']) && isset($params['api_id'])) {
                $this->add_api_movie($params['api_name'], $params['api_id']);
            }
            else
                $toReturn = array('code' => 1);


//             if (isset($params['movieIdInDB']))
//                 $return = $this->add_db_movie($params['movieIdInDB']);
//             elseif (isset($params['api_name']) && isset($params['api_id']))
//                 $return = $this->add_api_movie($params['api_name'], $params['api_id']);
//             else {
//                 $this->_response->clearBody();
//                 $this->_response->clearHeaders();
//                 $this->_response->setHttpResponseCode(406);
//             }
        }
        catch (Exception $e) {
            $this->_logger->err("[EXCEPTION] {$e->getFile()}:{$e->getLine()} - {$e->getMessage()}");
            //$this->_logger->debug(print_r($e, true));
            $toReturn = array('code' => 1);
        }
        $this->_helper->json($toReturn);
    }

    /**
     * @param string $api_name
     * @param int $api_id
     */
    private function add_api_movie($api_name, $api_id) {

        // FIXME
        if ($api_name != 'TMDB')
            throw new ErrorException("API non geree <$api_name>");

        $options = Zend_Registry::get('Zend_Config');
        $pluginName = $options['movie_plugin'];
        $pluginClass = "MAPI_$pluginName";
        $apiInstance  = new $pluginClass();
        $apiInstance->logger = $this->_logger;

        $movieMapper = new App_Model_MovieMapper();

        $userId = $this->_connection->id;

        // verifier si le film est en base
        $idMovie = $movieMapper->getMovieIdByAPI($api_name, $api_id);

        /**
         * Etape 1 : creation du film s'il n'a pas deja ete ajouté
         */
        if ($idMovie == -1) {

            //    rechercher les details
            $api_params['lang'] = substr($options['defaultLocale'], 0, 2);
            $api_params['proxy'] = (isset($options['proxy']) ? $options['proxy'] : '');
            $apiInstance->setParams($api_params);
            $movieDetails = $apiInstance->getMovieDetails($api_id); // MAPI_Model_Movie

//             $this->_logger->debug("=== movieDetails ===");
//             $this->_logger->debug($movieDetails);

            // add movie
            $name = $movieDetails->o_title;
            $nameFr = $movieDetails->o_title;
            $urlPicture = $movieDetails->poster;
            $rating = 0;
            $dateOut = $movieDetails->production_year;
            $createdBy = -1;
            $description = $movieDetails->plot;
            $api_name = 'TMDB';
            $api_idMovie = $movieDetails->id;
            $this->_logger->info("[add_api_movie] ajout du film : $name - api<$api_name>id<$api_idMovie>");
            $movieMapper->addMovie($name, $nameFr, $urlPicture, $rating, $dateOut, $createdBy, $description, $api_name, $api_idMovie);

            // recup id
            $idMovie = $movieMapper->getMovieIdByAPI($api_name, $api_id);
            if ($idMovie == -1)
                throw new ErrorException("Erreur lors de l'ajout du film");
        }

        /**
         * Etape 2 : creation du lien entre le film et l'utilisateur
         */
        if ($movieMapper->linkExists($userId, $idMovie))
            throw new ErrorException("[add_api_movie] le lien existe deja");

        $this->_logger->info("[add_api_movie] ajout du lien userMovie : userId<$userId> idMovie<$idMovie>");
        $movieMapper->linkUserToMovie($userId, $idMovie);
    }

    /**
     *
     * @param unknown_type $idMovie
     */
//     private function add_db_movie($idMovie) {

//         $returnSuccess = false;
//         $returnmessage = '';

//         $movieMapper = new App_Model_MovieMapper();

//         $userId = $this->_connection->id;

//         // verifier si le film est en base
//         if (!$movieMapper->movieExists($idMovie))
//             $returnmessage = 'le film n\'existe pas';
//         else {
//             // verifier si le lien est en base
//             if ($movieMapper->linkExists($userId, $idMovie))
//                 $returnmessage = 'le lien existe deja';
//             else {
//                 // ajouter rt_user_movie
//                 $movieMapper->linkUserToMovie($userId, $idMovie);
//                 $returnSuccess = true;
//             }
//         }

//         array('success' => $returnSuccess, 'message' => $returnmessage);
//     }
}

